package com.wy.authority.controller;

import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskInfoQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 忘忧
 * @Date Created in 2021/1/25 14:15
 * @Description:
 */
@RestController
public class flowableController {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngine processEngine;

    //新增
    @GetMapping("/add")
    public String add(String user,Integer time ,String reason){
        //启动流程
        HashMap<String,Object> map = new HashMap<>();
        map.put("user",user);
        map.put("time",time);
        map.put("reason",reason);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("qj", map);
        return "提交成功,流程ID为：" + processInstance.getId();
    }

    // 查询的是当前节点
    @GetMapping("/list")
    public String list( String processInstanceId){
        Task task = taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult(); // 查询的是当前节点
        return task.toString();
    }

    //查询任务
    @GetMapping("/rw")
    public void rw(){

    }



    //通过/拒绝任务
    @GetMapping("/apply")
    public String apply(String taskId, String approved){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return "流程不存在";
        }
        Map<String, Object> variables = new HashMap<>();
        Boolean apply = approved.equals("提交请假") ? true : false;
        variables.put("is", apply);
        taskService.complete(taskId, variables);
        return "请假已经提交" + approved;
    }

   @GetMapping("/dept")
    public String dept(String taskId, String approved){
       TaskService taskService = processEngine.getTaskService();
       List<Task> tasks3 = taskService.createTaskQuery().taskCandidateGroup("managers").list();
       System.out.println("你有 " + tasks3.size() + " 个待办任务:");
       for (int i = 0; i < tasks3.size(); i++) {
           System.out.println((i + 1) + ") " + tasks3.get(i).getName()+tasks3.get(i).getId());
       }
       Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
       List<Task> tasks = taskService.createTaskQuery().taskCandidateUser("bm").list();
       System.out.println("待签收列表"+tasks);
       taskService.claim(task.getId(), "bm");

       if (task == null) {
           return "流程不存在";
       }
       Map<String, Object> variables = new HashMap<>();
       variables.put("tg", approved);
       List<Task> task2 = taskService.createTaskQuery().taskAssignee("bm").list();
       System.out.println("已签收列表"+task2);
       taskService.complete(taskId, variables);
       return "部门主管审批是否通过：" + approved;
    }


    @GetMapping("/rs")
    public String rs(String taskId, String approved){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return "流程不存在";
        }
        Map<String, Object> variables = new HashMap<>();
        variables.put("dj", approved);
        taskService.complete(taskId, variables); //通过跳转到下一个任务
        return "人事是否通过：" + approved;
    }


    @GetMapping("boss")
    public String boss(String taskId, String approved) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return "流程不存在";
        }
        Map<String, Object> variables = new HashMap<>();
        variables.put("tg", approved);
        taskService.complete(taskId, variables);
        return "总经理审批是否通过：" + approved;

    }

    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @RequestMapping(value = "processDiagram")
    public void genProcessDiagram(HttpServletResponse httpServletResponse, String processId) throws Exception {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();

        //流程走完的不显示图
        if (pi == null) {
            return;
        }
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
        String InstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(InstanceId)
                .list();

        //得到正在执行的Activity的Id
        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    //查看历史流程记录
    @GetMapping("historyList")
    public Object getHistoryList(String processInstanceId) {
        List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId).finished().orderByHistoricActivityInstanceEndTime().asc().list();
        return historicActivityInstances;
    }

    /**
     * 退回到指定任务节点
     *
     * @param currentTaskId 当前任务ID
     * @param targetTaskKey 目标任务节点key
     * @throws Exception
     * @Author 包海鹏
     */
    @GetMapping("/backToStep")
    public void backToStep(String currentTaskId, String targetTaskKey) throws Exception {

        Task currentTask = taskService.createTaskQuery().taskId(currentTaskId).singleResult();
        System.out.println(currentTask);
        if (currentTask == null) {
            throw new Exception("当前任务节点不存在");
        }
        List<String> currentTaskKeys = new ArrayList<>();
        currentTaskKeys.add(currentTask.getTaskDefinitionKey());
        System.out.println(currentTaskKeys);
                 runtimeService.createChangeActivityStateBuilder()
                .processInstanceId(currentTask.getProcessInstanceId())
                .moveActivityIdsToSingleActivityId(currentTaskKeys, targetTaskKey)
                .changeState();
    }

   @GetMapping("/test")
   public void back(String picetanceId){
       runtimeService.createChangeActivityStateBuilder()
               .processInstanceId(picetanceId)
               .moveActivityIdTo("sid-AE515F33-90D8-4F7B-9B7B-27B082996B29", "sid-B453ADA2-A76B-4FCE-A20D-90B506B6519C")
               .changeState();
   }
    //查询所有节点
    @GetMapping("listAll")
    public Object listAll() {
        TaskInfoQueryWrapper taskInfoQueryWrapper = runtimeService != null
                ? new TaskInfoQueryWrapper(taskService.createTaskQuery())
                : new TaskInfoQueryWrapper(historyService.createHistoricTaskInstanceQuery());
        return taskInfoQueryWrapper;
    }



    //转办任务，只是改变当前任务的办理人而已，不会产生流转记录。
    @GetMapping("zhuang")
   public void send(String TaskId, String curUserId, String acceptUserId){
        taskService.deleteCandidateUser(TaskId,curUserId);
        taskService.addCandidateUser(TaskId,acceptUserId);
    }

   //转办
    @GetMapping("/zhuangban")
    public String zhuangban(String currentTaskId, String targetTaskKey) throws Exception {

        Task currentTask = taskService.createTaskQuery().taskId(currentTaskId).singleResult();
        System.out.println(currentTask);
        if (currentTask == null) {
            throw new Exception("当前任务节点不存在");
        }
        List<String> currentTaskKeys = new ArrayList<>();
        currentTaskKeys.add(currentTask.getTaskDefinitionKey());
        System.out.println(currentTaskKeys);
        runtimeService.createChangeActivityStateBuilder()
                .processInstanceId(currentTask.getProcessInstanceId())
                .moveActivityIdsToSingleActivityId(currentTaskKeys, targetTaskKey)
                .changeState();

        return "转办成功";
    }

    //委派
    @GetMapping("sign")
    public String sign(String taskId ,String curUserId,String acceptUserId,String ap){
        taskService.setOwner(taskId, curUserId);
        taskService.delegateTask(taskId,acceptUserId);
        Map<String, Object> variables = new HashMap<>();
        variables.put("sign",ap);
        taskService.resolveTask(taskId, variables);
        return "委派成功";
    }

}
